package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.adapter.LuckDrawGvAdapter;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.AppTools;
import com.eims.sls_app.view.MyToast;
import com.eims.sls_app.view.Rotate3dAnimation;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import bls.juejin.cn.R;


public class Luck_drawActivity extends MyBaseActivity implements OnClickListener, OnItemClickListener {
	private static final String TAG = "Luck_drawActivity";
	private TextView tv_chance;
	private GridView gv_luck_draw;
	private ImageView btn_back;
	private int pos;
	private int count = 0;
	private int num;
	private MyHandler myHandler;
	private MyAsynTask myAsynTask;
	private String opt, auth, info, time, imei, crc, key; // 格式化后的参数
	private String[] SchemeNumber;
	private String[] DataTime;
	private LuckDrawGvAdapter luckDrawGvAdapter;
	private List list;
	private int[] arr;
	private int[] pic2=new int[9];
	private String[] title2 = new String[9];
	private int[] timg1 = {R.drawable.timg1_0, R.drawable.timg1_1, R.drawable.timg1_2, R.drawable.timg1_3, R.drawable.timg1_4, R.drawable.timg1_5, R.drawable.timg1_6, R.drawable.timg1_7, R.drawable.timg1_8};
	private int[] timg2 = {R.drawable.timg2_0, R.drawable.timg2_1, R.drawable.timg2_2, R.drawable.timg2_3, R.drawable.timg2_4, R.drawable.timg2_5, R.drawable.timg2_6, R.drawable.timg2_7, R.drawable.timg2_8};
	private int[] timg3 = {R.drawable.timg3_0, R.drawable.timg3_1, R.drawable.timg3_2, R.drawable.timg3_3, R.drawable.timg3_4, R.drawable.timg3_5, R.drawable.timg3_6, R.drawable.timg3_7, R.drawable.timg3_8};
	private int[] timg4 = {R.drawable.timg4_0, R.drawable.timg4_1, R.drawable.timg4_2, R.drawable.timg4_3, R.drawable.timg4_4, R.drawable.timg4_5, R.drawable.timg4_6, R.drawable.timg4_7, R.drawable.timg4_8};
	private int[] img = {R.drawable.buy_zq_jgg_1, R.drawable.buy_zq_jgg_2, R.drawable.buy_zq_jgg_3, R.drawable.buy_zq_jgg_4, R.drawable.buy_zq_jgg_5, R.drawable.buy_zq_jgg_6, R.drawable.buy_zq_jgg_7, R.drawable.buy_zq_jgg_8, R.drawable.buy_zq_jgg_9};
	private int[] pic={R.drawable.buy_zq_gyj_acmilan, R.drawable.buy_zq_gyj_huangma, R.drawable.buy_zq_gyj_asinna,
			R.drawable.buy_zq_gyj_bairenmonihei, R.drawable.buy_zq_gyj_madelijingji, R.drawable.buy_zq_gyj_basailuona,
			R.drawable.buy_zq_gyj_manlian, R.drawable.buy_zq_gyj_manshesitecheng, R.drawable.buy_zq_gyj_qierxi};
	private String[] title = {"0","0","1.00","5.00","1.00","2.00","2.00","0","0"};
	private static final int SEND_SMS_REQUEST = 0;    
	private static final int CALL_REQUEST = 1;   
	
	
	private TextView tvShowInfo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_luck_draw);
		myHandler = new MyHandler();
		App.activityS.add(this);
		App.activityS1.add(this);
		initView();
		initData();
		setListener();
	}

	private void setListener() {
		btn_back.setOnClickListener(this);
		gv_luck_draw.setOnItemClickListener(this);
	}

	private void initData() {
		myAsynTask = new MyAsynTask();
		myAsynTask.execute();
		list = new ArrayList();
		//list.add(pic);

		list.add(timg1);
		list.add(timg2);
		list.add(timg3);
		list.add(timg4);
		Random random = new Random();
		num = random.nextInt(4);

		luckDrawGvAdapter = new LuckDrawGvAdapter(getApplicationContext(), (int[]) list.get(num));
		gv_luck_draw.setAdapter(luckDrawGvAdapter);
		upData();

		setchangTextView(count);



	}

	private void upData() {
		arr = new int[9];
		for(int i=0;i<arr.length;i++){
			arr[i]=i;
		}

		//交换数组中的两个元素值
		for(int i=0;i<arr.length;i++){
			swap(arr,i,randInt(i,arr.length-1));
		}

		//输出随机后的数组值
		for(int i=0;i<arr.length;i++){
			System.out.println(arr[i]+" ");
			for (int j = i; j < arr.length; j++) {
				pic2[j] = pic[arr[i]];
				title2[j] = title[arr[i]];
				/*luckDrawGvAdapter = new LuckDrawGvAdapter(getApplicationContext(), pic2);
		        gv_luck_draw.setAdapter(luckDrawGvAdapter);*/
			}
			//tv_chance.setText("你还有"+arr+"次抽奖机会");


			if((i+1)%10==0)
				System.out.println();
		}
	}

	private void setchangTextView(int pos) {
		if (pos==0) {//你已经没有抽奖机会了
			Spanned text = Html.fromHtml(AppTools.changeStringColor("#09090A", "抽奖机会已用完"));
			tv_chance.setText(text);
		}else {
			Spanned text = Html.fromHtml("您还有 "
					+ AppTools.changeStringColor("#09090A", pos + "")+ " 次抽奖机会");
			tv_chance.setText(text);
		}

	}

	private void initView() {
		btn_back = (ImageView) findViewById(R.id.btn_back);
		tv_chance = (TextView) findViewById(R.id.tv_chance);
		gv_luck_draw = (GridView)findViewById(R.id.gv_luck_draw);

	}



	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
			case R.id.btn_back:
				finish();
				//backToHall();
				break;

			default:
				break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN) {
			finish();
			//	backToHall();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 返回首页
	 */
	public void backToHall() {
		Intent intent = new Intent(getApplicationContext(), MainActivity.class);
		this.startActivity(intent);
		this.finish();
	}

	//randInt()函数的实现
	private int randInt(int x,int y){
		//return (int)(Math.random()*100%(y-x+1)+x);//这个算法还是不好
		return (int)(Math.random()*(y-x+1)+x);
	}

	//实现swap()方法
	private void swap(int[] arr,int x,int y){
		int temp ;
		temp = arr[x];
		arr[x] = arr[y];
		arr[y] = temp;
	}

	/** 异步任务 */
	class MyAsynTask extends AsyncTask<Void, Integer, String> {





		/** 在后台执行的程序 */
		@Override
		protected String doInBackground(Void... params) {
			int p;
			info = "";

			//Log.i("x", "获得我全部投注记录    info  " + info);

			opt = "82";
			if (App.user==null) {
				crc = RspBodyBaseBean.getCrc(time, imei, key, info,
						"-1");
				auth = RspBodyBaseBean.getAuth(crc, time, imei,
						"-1");
			}else {
				crc = RspBodyBaseBean.getCrc(time, imei, key, info,
						App.user.getUid());
				auth = RspBodyBaseBean.getAuth(crc, time, imei,
						App.user.getUid());
			}

			Log.i(TAG,"抽奖>"+ RequestParams.convertParams(Luck_drawActivity.this, opt, info));
			String[] values = { opt, auth, info };
			String result = HttpUtils.doPost(App.names, values,
					App.path);

			Log.e("x", "得到所有抽奖内容   " + result);
			// MyToast.getToast(context, result);

			if ("-500".equals(result))
				return result;

			if (null == result)
				return "1";
			// 04-06 10:22:49.214: I/qtaguid(1826): Untagging socket 88 failed
			// errno=-13

			try {

				JSONObject item = new JSONObject(result);

				count = item.optInt("count");

				JSONArray array;
				try {
					array = new JSONArray(item.optString("list"));
					if (array==null) {
						return "1";
					}else {
						SchemeNumber = new String[array.length()];
						DataTime = new String[array.length()];

						for (int i = 0; i < array.length(); i++) {
							try {

								JSONObject items = array.getJSONObject(i);

								SchemeNumber[i] = items.optString("SchemeNumber");
								DataTime[i] = items.optString("DateTime");
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}


				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


				if (this.isCancelled()) {
					Log.i("x", "取消了异步。。。。");
					return null;
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.i("x", "myAllLottery 错误" + e.getMessage());
			}

			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			if (null == result)
				return;
			if ("1".equals(result)) {
				myHandler.sendEmptyMessage(-1);
			}

			myHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	/** 进行页面刷新 */
	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 0:
					setchangTextView(count);
					break;
				case -1:
					Toast.makeText(getApplication(), "数据为空", Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
			super.handleMessage(msg);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {


		if (count==0) {
			MyToast.getToast(getApplicationContext(), "你已经没有抽奖机会了").show();
		}else {


			LinearLayout layout = (LinearLayout) arg1;
			int a = arg2;
			View b = arg1;
			float centerX =arg1.getWidth() / 2.0f;
			float centerY = arg1.getHeight() / 2.0f;
			turnPic(centerX,centerY,layout,a,b);  //旋转方法
			//pos = pos-1;
			count -= 1;
			setchangTextView(count);
			Intent intent = new Intent(Luck_drawActivity.this,RedPacketActivity.class);
			intent.putExtra("money", title2[arg2]);
			intent.putExtra("SchemeNumber", SchemeNumber[count]);
			intent.putExtra("pic", pic2[arg2]);
			startActivityForResult(intent, SEND_SMS_REQUEST);
		}


	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) { // 如果返回码是可以用的
			switch (requestCode) {
				case SEND_SMS_REQUEST:
					//Toast.makeText(this, "数据打乱", Toast.LENGTH_SHORT).show();
					upData();
					break;


			}
		}
	}

	public void turnPic(float x,float y,LinearLayout ll,int a,View b){
		final LinearLayout layout =ll;
		final   float centerX =x;
		final   float centerY = y;
		final View view = b;
		final int position=a;

		Rotate3dAnimation rotation = new Rotate3dAnimation(0, 90, centerX,centerY, 200.0f, true);
		rotation.setDuration(500);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationEnd(Animation arg0) {
				//动画结束
				secondImationEnd(centerX,centerY,layout,view,position);//跳到下面
			}
			public void onAnimationRepeat(Animation arg0) {
			}
			@Override
			public void onAnimationStart(Animation arg0) {
			}
		});


		layout.startAnimation(rotation);
	}
	//另张图

	public void secondImationEnd(float x ,float y, LinearLayout ll,View b,int c){
		final View view =b ;
		final  int position= c;
		final   float centerX =x;
		final   float centerY = y;
		final LinearLayout layout = ll;

		//图片是用android:src不是android:background,所以使用setImageResource就可以实现图片翻转了。
		//实现翻转后再翻回来，要设置正反面标志位
		ImageView second = (ImageView)view.findViewById(R.id.iv_lucky);
		int[] image = (int[]) list.get(num);
		second.setImageResource(image[position]);
		Rotate3dAnimation rotatiomAnimation = new Rotate3dAnimation(-90, 0, centerX, centerY, 200.0f, false);
		rotatiomAnimation.setDuration(500);
		rotatiomAnimation.setInterpolator(new DecelerateInterpolator());
		second.startAnimation(rotatiomAnimation);


	}

}
